import requests
import asyncio
from playwright.async_api import async_playwright
from html2text import HTML2Text
import json

def wenzhen_paipan(name, sex, birthday, native_place="北京,北京市,东城区", is_solar=True, paipan_type=1, client_platform="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0"):
    """
    发送排盘 POST 请求并处理响应
    :param name: 姓名
    :param sex: 性别代码（'1' 代表男，'0' 代表女）
    :param birthday: 生日，格式为 "%Y-%m-%d %H:%M:%S"
    :param native_place: 出生地，默认为 "北京,北京市,东城区"
    :param is_solar: 是否为阳历，默认为 True
    :param paipan_type: 类型，默认为基本命盘 1，专业细盘为 2
    :param client_platform: 客户端平台信息，默认为 "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0"
    :return: 合并排盘结果和五行能量结果的字典或 None
    """
    gender = "男" if sex == '1' else "女"
    result = None
    status_msg = "请求失败，未成功返回结果"
    # 硬编码的 URL 常量
    URL = "https://bz.zhuangdy.net/zhuangdayun-xiaochengxu/account/paipan"
    # 设置请求头
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0",
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Referer": "http://paihaoyun.qiazhiyisuan.com/",
        "content-type": "application/json",
        "token": "1",
        "Origin": "http://paihaoyun.qiazhiyisuan.com",
        "Connection": "keep-alive",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "Priority": "u=4"
    }
    # 组装请求数据
    data = {
        "name": name,
        "sex": sex,
        "birthday": birthday,
        "nativePlace": native_place,
        "isSolar": is_solar,
        "type": paipan_type,
        "clientPlatform": client_platform
    }
    try:
        # 发送 POST 请求
        response = requests.post(URL, json=data, headers=headers)

        # 检查响应状态码
        if response.status_code == 200:
            paipan_result = response.json().get('result')
            if paipan_result:
                # 提取天干地支
                # 假设天干地支信息在 nianyuerishi 字段中，且格式为 [天干列表, 地支列表]
                nianyuerishi = paipan_result.get('nianyuerishi', [])
                if len(nianyuerishi) >= 2:
                    tiangandizhi = nianyuerishi[1] + nianyuerishi[2]
                    # 查询五行能量
                    wuxing_energy = get_wuxing_energy(tiangandizhi, paipan_type)
                    if wuxing_energy:
                        # 合并结果
                        paipan_result['wuxing_energy'] = wuxing_energy
                    result = paipan_result
                    status_msg = "请求成功返回结果"
    except requests.RequestException as e:
        print(f"请求发生错误: {e}，数据: {data}")
    
    print(f"输入信息 - 姓名: {name}, 性别: {gender}, 出生日期和时间: {birthday}, 状态: {status_msg}")
    return result



def get_wuxing_energy(tiangandizhi, paipan_type=1):
    """
    发送获取五行能量的 POST 请求并处理响应
    :param tiangandizhi: 天干地支列表
    :param paipan_type: 类型，默认为 1
    :return: 响应的 JSON 数据或 None
    """
    URL = "https://bz.zhuangdy.net/zhuangdayun-xiaochengxu/account/getWuxingEnergy"
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0",
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Referer": "http://paihaoyun.qiazhiyisuan.com/",
        "content-type": "application/json",
        "token": "1",
        "Origin": "http://paihaoyun.qiazhiyisuan.com",
        "Connection": "keep-alive",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "Priority": "u=4"
    }
    data = {
        "tiangandizhi": tiangandizhi,
        "type": paipan_type
    }
    try:
        response = requests.post(URL, json=data, headers=headers)
        if response.status_code == 200:
            return response.json().get('result')
        else:
            print(f"获取五行能量请求失败，状态码: {response.status_code}，数据: {data}")
            return None
    except requests.RequestException as e:
        print(f"获取五行能量请求发生错误: {e}，数据: {data}")
        return None

def to_markdown(page_content):
    """
    使用html2text将HTML内容转换为优化后的Markdown
    :param page_content: HTML字符串
    :return: 优化后的Markdown字符串
    """
    h = HTML2Text()
    h.body_width = 0  # 禁用自动换行
    h.ignore_links = False
    h.ignore_images = True
    h.ignore_mailto_links = True
    h.bypass_tables = True  # 启用表格转换
    h.mark_code = True  # 保留代码块标记
    h.wrap_links = False
    md = h.handle(page_content)
    # md = '\n'.join([line.strip() for line in md.splitlines() if len(line.strip()) > 0])
    return md
    
async def crawl_paipan(name, gender, birth_date, location):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        await page.goto('https://pcbz.iwzwh.com/#/paipan/index')

        # 定位到 div.el-input 元素
        div_el_input = await page.query_selector('div.el-input')
        if div_el_input:
            # 定位到 div.el-input 下面的 input 元素
            name_input = await div_el_input.query_selector('input')
            if name_input:
                await name_input.fill(name)

        # 选择性别
        if gender == 1:
            await page.click('.form-row-item-sex:nth-child(1) > img')
        else:
            await page.click('.form-row-item-sex:nth-child(2) > img')

        # 定位日期输入框
        birth_date_input = await page.query_selector('.input-box:nth-child(3) > .bogus-input')
        if birth_date_input:
            # 点击输入框，弹出日期时间选择器
            await birth_date_input.click()
            # 将 datetime.datetime 格式化为 199303270255 格式
            formatted_date = birth_date.strftime("%Y%m%d%H%M")
            # 定位对话框中的输入框
            date_dialog_input = await page.query_selector('input.datetime_search_input:nth-child(1)')
            if date_dialog_input:
                # 填入日期
                await date_dialog_input.fill(formatted_date)
                fill_confirm_button = await page.query_selector('.datetime_search_btn')
                if fill_confirm_button:
                    await fill_confirm_button.click()
                    # 点击提交按钮
                    confirm_button = await page.query_selector('span.datetime_confirm:nth-child(4)')
                    if confirm_button:
                        await confirm_button.click()

        # 选择出生地
        if location != "未知":
            location_input = await page.query_selector('.input-box:nth-child(4) > .bogus-input')
            if location_input:
                await location_input.click()
                location_item = await page.query_selector(f"//div[contains(text(),'{location}')]")
                if location_item:
                    await location_item.click()

                    # 点击提交按钮
                    confirm_button = await page.query_selector("div[id='datetime_box'] span[class='datetime_confirm']")
                    if confirm_button:
                        await confirm_button.click()

        # 使用新的提交按钮选择器
        async with page.context.expect_page() as new_page_info:
            await page.click('div.form_paipan')
        new_page = await new_page_info.value

        # 等待新页面加载完成
        await new_page.wait_for_load_state('networkidle')

        # 保存基本排盘页面中 div.paipan-result-content 的截图
        result_content = await new_page.query_selector('div.base-pan-box')
        # basic_paipan_screenshot_path = '基本排盘.png'
        # await result_content.screenshot(path=basic_paipan_screenshot_path)
        # 导出基本排盘的 Markdown
        basic_paipan_page_content = await result_content.inner_html()
        basic_paipan_markdown = to_markdown(basic_paipan_page_content)
        # basic_paipan_html = basic_paipan_page_content
        # with open('基本排盘.md', 'w', encoding='utf-8') as f:
        #     f.write(basic_paipan_markdown)
        # with open('基本排盘.html', 'w', encoding='utf-8') as f:
        #     f.write(basic_paipan_html)

        # 选中 div.paipan-result-sidebar 下名为基本信息的 item
        basic_info_item = await new_page.query_selector('div.paipan-result-sidebar :text("基本信息")')
        if basic_info_item:
            await basic_info_item.click()
            # 等待页面更新完成
            await new_page.wait_for_load_state('networkidle')
            
            # 保存基本信息页面中 div.paipan-result-content 的截图
            result_content = await new_page.query_selector('div.base-msg-box')
            # basic_info_screenshot_path = '基本信息.png'
            # await result_content.screenshot(path=basic_info_screenshot_path)
            # 导出基本信息的 Markdown
            basic_info_page_content = await result_content.inner_html()
            basic_info_markdown = to_markdown(basic_info_page_content)
            # basic_info_html = basic_info_page_content
            # with open('基本信息.md', 'w', encoding='utf-8') as f:
            #     f.write(basic_info_markdown)
            # with open('基本信息.html', 'w', encoding='utf-8') as f:
            #     f.write(basic_info_html)

            # 点击 div.base-msg-wuxingbar-tabs-item:nth-child(3)
            tab_3 = await new_page.query_selector('div.base-msg-wuxingbar-tabs-item:nth-child(3)')
            if tab_3:
                await tab_3.click()
                # 等待页面更新完成
                await new_page.wait_for_load_state('networkidle')
                # 保存截图
                result_content = await new_page.query_selector('div.base-msg-wuxingbar')
                # basic_info_wuxing_count_screenshot_path = '基本信息_五行个数.png'
                # await result_content.screenshot(path=basic_info_wuxing_count_screenshot_path)
                basic_info_wuxing_count_content = await result_content.inner_html()
                basic_info_wuxing_count_markdown = to_markdown(basic_info_wuxing_count_content)

            # 点击 div.base-msg-wuxingbar-tabs-item:nth-child(4)
            tab_4 = await new_page.query_selector('div.base-msg-wuxingbar-tabs-item:nth-child(4)')
            if tab_4:
                await tab_4.click()
                # 等待页面更新完成
                await new_page.wait_for_load_state('networkidle')
                # 保存截图
                result_content = await new_page.query_selector('div.base-msg-wuxingbar')
                basic_info_hancanggan_count_content = await result_content.inner_html()
                basic_info_hancanggan_count_markdown = to_markdown(basic_info_hancanggan_count_content)
                # basic_info_hancanggan_count_screenshot_path = '基本信息_含藏干数.png'
                # await result_content.screenshot(path=basic_info_hancanggan_count_screenshot_path)

            # 合并两个 Markdown 文件
            combined_markdown = basic_info_markdown + '\n\n' + basic_paipan_markdown
            with open('合并结果.md', 'w', encoding='utf-8') as f:
                f.write(combined_markdown)
        else:
            print("未找到名为基本信息的 item")

        await browser.close()

        # 合并结果
        combined_result = {}
        combined_result['基本信息'] = {}
        basic_info_markdown_lines = basic_info_markdown.splitlines()
        for i in range(0, 72, 4):
            key = basic_info_markdown_lines[i].strip()
            value = basic_info_markdown_lines[i+2].strip()
            combined_result['基本信息'][key] = value

        birth_location = combined_result["基本信息"]["出生地区"]
        combined_result["基本信息"]["出生地区"] = birth_location.split(" ")[0]

        key = basic_info_markdown_lines[78].strip()
        value = basic_info_markdown_lines[80].strip()
        combined_result['基本信息'][key] = value
        
        basic_info_wuxing_count_markdown_lines = basic_info_wuxing_count_markdown.splitlines()
        combined_result['五行'] = {}
        basic_info_wuxing_count_markdown_lines = basic_info_wuxing_count_markdown.splitlines()
        combined_result['五行']['五行个数'] = {}
        for i in range(6, 23, 4):
            key = basic_info_wuxing_count_markdown_lines[i].strip()
            value = basic_info_wuxing_count_markdown_lines[i+2].strip()
            combined_result['五行']['五行个数'][key] = value

        basic_info_hancanggan_count_markdown_lines = basic_info_hancanggan_count_markdown.splitlines()
        combined_result['五行']['含藏干数'] = {}
        for i in range(6, 23, 4):
            key = basic_info_hancanggan_count_markdown_lines[i].strip()
            value = basic_info_hancanggan_count_markdown_lines[i+2].strip()
            combined_result['五行']['含藏干数'][key] = value

        combined_result['基本排盘'] = []
        basic_paipan_markdown_lines = basic_paipan_markdown.splitlines()
        for i in range(0, 11):
            row = []
            for j in range(0, 10, 2):
                row.append(basic_paipan_markdown_lines[i*10 + j].strip())
            combined_result['基本排盘'].append(row)


        with open('合并结果.json', 'w', encoding='utf-8') as f:
            json.dump(combined_result, f, indent=4, ensure_ascii=False)
        
        return combined_result
        # 组合截图文件路径成字典
        # screenshot_paths = {
        #     '基本排盘': basic_paipan_screenshot_path,
        #     '基本信息': basic_info_screenshot_path,
        #     '基本信息_五行个数': basic_info_wuxing_count_screenshot_path if 'basic_info_wuxing_count_screenshot_path' in locals() else None,
        #     '基本信息_含藏干数': basic_info_hancanggan_count_screenshot_path if 'basic_info_hancanggan_count_screenshot_path' in locals() else None
        # }

        # return screenshot_paths
